import 'package:eshi/app/shi/data/System.dart';
import 'package:eshi/app/shi/widget/CommonWidgets.dart';
import 'package:eshi/main.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:eshi/app/shi/data/parse/FileParser.dart';

/// 音频播放组件
class AudioTextWidget extends StatefulWidget {
  final String text;
  final Widget? children;

  String audioAssetPath="";  // 音频资源路径，如 'assets/audio/example.mp3'
  TextStyle? style;
  AudioTextWidget({super.key,this.text="",this.children}){
      audioAssetPath = FileParser.getAudio(text);
  }



  @override
  AudioTextWidgetState createState() => AudioTextWidgetState();
}

class AudioTextWidgetState extends State<AudioTextWidget> {
  //用于单一播放用 
  static  AudioTextWidgetState? lastPlaying;
  final AudioPlayer _audioPlayer = AudioPlayer();
  bool _isPlaying = false;
  Duration _duration = Duration.zero;
  Duration _position = Duration.zero;
   // 预设速度选项
  final List<double> _presetSpeeds = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0,3.0,5.0].reversed.toList();
  double _currentSpeed=1.0;
  bool isShowSpeed = false;
  bool _isDragging = false;
  @override
  void initState() {
    super.initState();
    _initAudioPlayer();
  }

  // 初始化音频播放器
  void _initAudioPlayer() {
    _audioPlayer.onPlayerStateChanged.listen((PlayerState state) {
      setState(() => _isPlaying = state == PlayerState.playing);
      if(_isPlaying) lastPlaying = this;
    });

    _audioPlayer.onDurationChanged.listen((Duration duration) {
      setState(() => _duration = duration);
    });

    _audioPlayer.onPositionChanged.listen((Duration position) {
      if(!_isDragging){
        process = _position.inSeconds/_duration.inSeconds;
        setState(() => _position = position);
      }
    });

    _audioPlayer.onPlayerComplete.listen((_) {
      setState(() {
        _isPlaying = false;
        _position = Duration.zero;
      });
    });
  }

  // 播放或暂停音频
  Future<void> _playOrPause() async {
    if (_isPlaying) {
      await _audioPlayer.pause();
    } else {
       // 从 assets 加载音频
      if(widget.audioAssetPath.isNotEmpty) {
        System.isPhone
        ?  await _audioPlayer.play(DeviceFileSource(widget.audioAssetPath))
        : await _audioPlayer.play(AssetSource(widget.audioAssetPath.substring("assets/".length)));
      }
      if(lastPlaying!=null && lastPlaying !=this) lastPlaying!._audioPlayer.pause();
    }
  }

  @override
  void dispose() {
    _audioPlayer.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return  widget.children!=null ?
         Row(
          mainAxisSize: MainAxisSize.min,
          children: [ 
            InkWell(
              child: widget.children!,
              onTap: () async{
               lastPlaying?._audioPlayer.pause();
               await simpleDialog(context: context, body:  AudioTextWidget(text: widget.text),title:widget.text);
               lastPlaying?._audioPlayer.pause();
              },
              onLongPress: (){
                customWidgetKey.currentState?.tabState?.onChangeName("audio",widget.text);
              },
            ),
            if(widget.audioAssetPath.isNotEmpty)
            InkWell(onTap: _playOrPause, child: Icon(
               _isPlaying ? Icons.pause_circle : Icons.play_circle,
                color: Colors.blue,
              )
            ),
            const SizedBox(width: 8),
            // 可选：显示音频进度
            if (_duration.inSeconds > 0)
              Text(
                '${_position.inSeconds}/${_duration.inSeconds}s',
                style: TextStyle(fontSize: 12, color: Colors.grey),
              ),
          ],
        )
        : Column(children: [ audioPlay()]);
  }

    // 格式化时长显示 (mm:ss)
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return "$minutes:$seconds";
  }
  get currentDuration => _formatDuration(_position);
  get totalDuration => _formatDuration(_duration);
  double process=0;

  Widget audioPlay(){
    final theme = Theme.of(context);
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 进度条滑块
        Slider(
          value: process,
          min: 0.0,
          max: 1.0,
          // 进度条颜色
          activeColor:  Colors.grey[700],
          inactiveColor: Colors.grey[700],
          // 滑块样式
          thumbColor:Theme.of(context).primaryColor,
          // thumbRadius: 8,
          // 拖动时的反馈
          // overlayColor: Colors.blueAccent,
          // overlayRadius: 12,
          // 拖动过程中实时更新
          onChanged: (value) {
             _isDragging = true;
            process = value;
            setState(() {
              // 计算拖动时的当前时长
              _position = Duration(
                seconds: (value * _duration.inSeconds).round(),
              );

            });
          },
          // 拖动结束时回调
          onChangeEnd: (value) {
             _isDragging = false;
             process = value;
             _audioPlayer
              ..seek(_position)
              ..resume();
          },
        ),
        // 时间显示（当前时间/总时长）
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 4),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment:CrossAxisAlignment.start,
            children: [
              Text(
                currentDuration,
                style: TextStyle(
                  color: Colors.grey[400],
                  fontSize: 12,
                ),
              ),
              Expanded(
                child: Stack(
                  children: [
                      Align(
                        alignment: Alignment.topCenter,
                        child: IconButton(
                            icon: Icon(  _isPlaying ? Icons.pause_circle : Icons.play_circle,
                                color: Colors.lightBlue,
                                size: 52,
                              ),
                            onPressed: _playOrPause
                          ),
                      ),
                      Align(
                        alignment: Alignment.bottomRight,
                        child:InkWell(
                          child:  Text("${_currentSpeed}x   "),
                          onTap: ()=> setState(() {
                            isShowSpeed = true;
                          })
                        )
                      )   
                  ]
                )
              ),
              Text(
                totalDuration,
                style: TextStyle(
                  color: Colors.grey[400],
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
        if(isShowSpeed)
         // 预设速度选项
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          padding: const EdgeInsets.symmetric(horizontal: 6),
          child: Row(
            children: _presetSpeeds.map((speed) {
              final isSelected = _currentSpeed == speed;
              return Padding(
                padding: const EdgeInsets.symmetric(horizontal: 4),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: isSelected 
                        ? theme.primaryColor 
                        : theme.scaffoldBackgroundColor,
                    foregroundColor: isSelected 
                        ? Colors.white 
                        : theme.textTheme.bodyLarge?.color,
                    side: BorderSide(
                      color: isSelected 
                          ? theme.primaryColor 
                          : theme.hintColor.withOpacity(0.3),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  onPressed: () {
                    setState(() {
                      _currentSpeed = speed;
                      setState(() {
                        isShowSpeed = false;
                      });
                      _audioPlayer.setPlaybackRate(speed);
                    });
                  },
                  child: Text(speed.toString()),
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}